package org.schat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description 灭霸的响指，发动后将随机消灭地球上一半的沙雕。
 * @Author lsh
 * @Date 2020-03-18 19:16
 **/
public class Thanos {
    private static AtomicLong version = new AtomicLong(0);
    private static Object lock = new Object();

    public static JSONObject snap(long value,ClientDomain requestClientDomain){
        JSONObject jsonObject = new JSONObject();
        //成为灭霸
        if(becomeAThanos(value)){
            synchronized (lock){
                String msg = requestClientDomain.getClientName()+"发动了灭霸的响指！";
                IMServer.msgQue.offer(new MessageDomain("1",msg));
                Collection<ClientDomain> clientDomainCollection = IMServer.clientMap.values();
                List<ClientDomain> clientDomainList = new ArrayList<>();
                clientDomainList.addAll(clientDomainCollection);
                //随机出一半的沙雕
                int clientNum = clientDomainList.size();
                int clearNum = 1;
                if(clientNum > 1){
                    //计算出一半沙雕数量(0.5个沙雕肯定无法存活，进行四舍五入操作)。
                    clearNum  = Math.round((float) clientNum / 2);
                }
                int[] clearIndexs = new int[clientNum];
                for(int i = 0 ;i < clearNum;i++){
                    randList(clearIndexs,clientNum);
                }
                //对天选之子进行沙雕操作
                StringBuffer stringBuffer = new StringBuffer();
                for(int i = 0;i <clientNum; i++ ){
                    if(clearIndexs[i] == 1){
                        ClientDomain clientDomain = clientDomainList.get(i);
                        String clientName = clientDomain.getClientName();
                        String clientId = clientDomain.getId();
                        String deadMsg = "";
                        if(clientId.equals(requestClientDomain.getId())){
                            deadMsg = "你被自己发动的灭霸响指消灭了！";
                        }else{
                            deadMsg = "你被"+clientName+"发动的灭霸响指消灭了！";
                        }
                        stringBuffer.append(clientName);
                        stringBuffer.append(",");
                        //通知被消灭的沙雕
                        JSONObject deadInfo = new JSONObject();
                        deadInfo.put("resultCode","-9999");
                        deadInfo.put("msg",deadMsg);
                        IMServer.sendMsgToClient(clientDomain.getSocket(),"4",deadInfo.toJSONString());
                        //关闭沙雕的连接,并把他们从服务器中移除
                        IMServer.removeClient(clientDomain);
                    }
                }
                //群发给其他幸存的沙雕
                 msg = "消灭了沙雕 "+stringBuffer.toString();
                IMServer.msgQue.offer(new MessageDomain("1",msg));

                jsonObject.put("resultCode","1");
                jsonObject.put("msg","success");
            }
        }else{
            jsonObject.put("resultCode","2");
            jsonObject.put("msg","become a Thanos fail!");
        }
        return  jsonObject;
    }

    public static void main(String[] args){
        int listSize = 10;
        int clearNum = listSize / 2;
        int[] clearIndexs = new int[listSize];
        for(int i = 0 ;i < clearNum;i++){
            randList(clearIndexs,listSize);
        }
        System.out.println(Arrays.toString(clearIndexs));
    }

    public static  void randList(int[] clearIndexs,int listSize){
        SecureRandom random = null;
        try {
            random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if(random != null){
            int index = random.nextInt(listSize);
            if(clearIndexs[index] == 0){
                clearIndexs[index] = 1;
                return;
            }else{
                randList(clearIndexs,listSize);
            }
        }
    }

    //如果当前值 == 预期值，则以原子方式将该值设置为给定的更新值
    private static boolean becomeAThanos(long expected){
        return version.compareAndSet(expected,expected++);
    }

    //获得灭霸的版本号
    public static long getThanosVersion(){
        return version.get();
    }
}
